<?php
namespace Swork;

/**
 * 配置管理器
 * Class Configer
 * @package Swork
 */
class Configer
{
    /**
     * 收集器
     * @var array
     */
    private static $collector = [];

    /**
     * 收集
     * @param array $env 环境
     * @return boolean
     */
    public static function collect($env)
    {
        //配置文件所在的目录
        $confDir = $env['root'] . 'config';
        if ($env['env'] != '')
        {
            $confDir .= $env['sep'] . $env['env'];
        }

        //遍历取到配置
        self::traversalCollect($env, $confDir, self::$collector);

        //检查是否缺少必须配置
        $result = true;
        if (!isset(self::$collector['server']))
        {
            Command::showTag('Config', 'Missing server setting');
            $result = false;
        }
        if (!isset(self::$collector['rpc']))
        {
            Command::showTag('Config', 'Missing rpc setting');
            $result = false;
        }
        if (!isset(self::$collector['frame']))
        {
            Command::showTag('Config', 'Missing frame setting');
            $result = false;
        }
        if (!isset(self::$collector['db']))
        {
            Command::showTag('Config', 'Missing DB setting');
            $result = false;
        }
        if (!isset(self::$collector['redis']))
        {
            Command::showTag('Config', 'Missing redis setting');
            $result = false;
        }

        //返回成功
        return $result;
    }

    /**
     * 取出（支持可深度取值）
     * @param string $name 键名（如：db:test:uri）
     * @param mixed $dft 默认值
     * @return mixed
     */
    public static function get(string $name, $dft = [])
    {
        $keys = explode(':', $name);
        $value = self::$collector;
        foreach ($keys as $key)
        {
            $value = $value[$key] ?? $dft;
        }
        return $value;
    }

    /**
     * @param array $env 环境配置
     * @param string $dir 当前目录
     * @param array $collector 收集对象
     */
    private static function traversalCollect(array $env, string $dir, array &$collector)
    {
        //获取文件列表
        $files = scandir($dir);

        //逐个检查
        foreach ($files as $item)
        {
            //忽略系统隐藏文件
            if ($item == '.' || $item == '..')
            {
                continue;
            }

            //
            $filepath = $dir . $env['sep'] . $item;
            if (is_dir($filepath))
            {
                $collector[$item] = [];
                self::traversalCollect($env, $filepath, $collector[$item]);
            }
            else
            {
                //php为后缀才提取参数
                preg_match('/(.*?)\.php$/', $item, $matches);
                if (empty($matches[1]))
                {
                    continue;
                }
                $collector[$matches[1]] = @include($filepath);
            }
        }
    }
}


